
package com.afd.ozblip.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.afd.ozblip.entity.SignEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.share.OAuth;
import com.afd.ozblip.share.ShareAction;
import com.afd.ozblip.share.ShareConfig;
import com.afd.ozblip.share.TokenStore;
import com.afd.ozblip.share.WeiboOAuthActivity;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.BitmapUtil;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.StringUtil;
import com.j256.ormlite.android.AndroidDatabaseConnection;
import com.j256.ormlite.dao.Dao;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.umeng.socialize.bean.MultiStatus;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMInfoAgent;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.MulStatusListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.exception.SocializeException;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddSignedActivity extends BaseActivity {

    /****************** 视图变量 **************************/
    private LinearLayout commonLeft;
    private LinearLayout commonRight;
    private ImageView uploadImageIv;
    private EditText signContentEt;
    private RatingBar signStarRb;
    private TextView limitTv;
    private CheckBox twitterCb;
    private CheckBox facebookCb;
    private CheckBox sinaCb;
    private CheckBox qqCb;

    /****************** 数据变量 **************************/
    private String businessId;
    private String businessName;
    private SignEntity draftSignInfo;
    private String fileBase64;
    private Bitmap headBitmap;
    private float signStar;
    private String signContent;
    private OzBlipApplication myApp;
    private Dao<SignEntity, Integer> signDao;

    private OAuthV2 oAuth;
    // sdk controller
    private UMSocialService mController = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signed);
        // 寻找视图
        findViews();
        // 设置监听
        setListeners();
        // 获取参数
        getBundle();
        // 设置视图
        setViews();
        mController = UMServiceFactory.getUMSocialService(ShareConfig.DESCRIPTOR,
                RequestType.SOCIAL);
    }

    /**
     * 寻找视图
     */
    public void findViews() {
        // 初始化APP
        this.myApp = (OzBlipApplication) getApplication();
        try {
            this.signDao = myApp.getDBHelper().getDao(SignEntity.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        this.commonLeft = (LinearLayout) findViewById(R.id.ll_common_left);
        this.commonRight = (LinearLayout) findViewById(R.id.ll_common_right);
        this.uploadImageIv = (ImageView) findViewById(R.id.iv_add_sign_image);
        this.signStarRb = (RatingBar) findViewById(R.id.rb_add_sign_star);
        this.signContentEt = (EditText) findViewById(R.id.et_add_sign_content);
        this.limitTv = (TextView) findViewById(R.id.tv_add_sign_limit);
        this.twitterCb = (CheckBox) findViewById(R.id.cb_share_twitter);
        this.facebookCb = (CheckBox) findViewById(R.id.cb_share_facebook);
        this.sinaCb = (CheckBox) findViewById(R.id.cb_share_sina);
        this.qqCb = (CheckBox) findViewById(R.id.cb_share_qq);
        // 初始化腾讯授权对象
        // oAuth = new OAuthV2(ShareConfig.QQ_Redirect_Uri);
        // oAuth.setClientId(ShareConfig.QQ_App_Key);
        // oAuth.setClientSecret(ShareConfig.QQ_App_Seret);
        // // 关闭OAuthV2Client中的默认开启的QHttpClient。
        // OAuthV2Client.getQHttpClient().shutdownConnection();
    }

    /**
     * 设置监听
     */
    public void setListeners() {
        View.OnClickListener addSignedClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_common_left:
                        Dialog alertDialog = new AlertDialog.Builder(
                                AddSignedActivity.this)
                                .setTitle("提示")
                                .setMessage("是否保存到草稿箱")
                                .setIcon(android.R.drawable.ic_menu_help)
                                .setPositiveButton("确定",
                                        new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                try {
                                                    AndroidDatabaseConnection conn = new AndroidDatabaseConnection(
                                                            myApp.getDBHelper()
                                                                    .getWritableDatabase(),
                                                            true);
                                                    signDao.setAutoCommit(conn,
                                                            false);
                                                    Savepoint point = conn
                                                            .setSavePoint("a");
                                                    SignEntity sign = new SignEntity();
                                                    sign.setSellerId(businessId);
                                                    sign.setSellerName(businessName);
                                                    sign.setSginNaiyo(signContentEt
                                                            .getText().toString());
                                                    sign.setSellerStar(signStarRb
                                                            .getRating());
                                                    sign.setSginDate(StringUtil
                                                            .getFormatData1(new Date()));
                                                    signDao.create(sign);
                                                    conn.commit(null);
                                                    signDao.commit(conn);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                                finish();
                                            }
                                        })
                                .setNegativeButton("取消",
                                        new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
                                                finish();
                                            }
                                        }).create();
                        alertDialog.show();
                        break;
                    case R.id.ll_common_right:
                        signStar = signStarRb.getRating();
                        signContent = signContentEt.getText().toString();
                        if (verifyData()) {
                            // 提交签到数据
                            requestAddSignData();
                            // 分享到社交平台
                            doShare();
                        }
                        break;
                    case R.id.iv_add_sign_image:
                        showImageMenuDialog();
                        break;
                    default:
                        break;
                }
            }
        };
        this.commonLeft.setOnClickListener(addSignedClick);
        this.commonRight.setOnClickListener(addSignedClick);
        this.uploadImageIv.setOnClickListener(addSignedClick);
        this.signContentEt.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                String mText = signContentEt.getText().toString();
                int len = mText.length();
                if (len <= ShareConfig.QQ_Text_Limit) {
                    len = ShareConfig.QQ_Text_Limit - len;
                    limitTv.setText(String.valueOf(len));
                } else {
                    String temp = mText.substring(0, ShareConfig.QQ_Text_Limit);
                    signContentEt.setText(temp);
                    limitTv.setText(0);
                }

            }
        });
        this.twitterCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 判断Twitter是否授权
                    if (UMInfoAgent.isOauthed(mContext, SHARE_MEDIA.TWITTER)) {
                        twitterCb.setChecked(true);
                    } else {
                        // 设置按钮选中状态为false
                        twitterCb.setChecked(false);
                        try {
                            mController.doOauthVerify(mContext, SHARE_MEDIA.TWITTER,
                                    new UMAuthListener() {
                                        @Override
                                        public void onError(SocializeException e,
                                                SHARE_MEDIA platform) {
                                        }

                                        @Override
                                        public void onComplete(Bundle value,
                                                SHARE_MEDIA platform) {
                                            if (value != null
                                                    && !TextUtils.isEmpty(value
                                                            .getString("uid"))) {
                                                Toast.makeText(mContext, "授权成功.",
                                                        Toast.LENGTH_SHORT).show();
                                                twitterCb.setChecked(true);
                                            } else {
                                                Toast.makeText(mContext, "授权失败",
                                                        Toast.LENGTH_SHORT).show();
                                                twitterCb.setChecked(false);
                                            }
                                        }

                                        @Override
                                        public void onCancel(SHARE_MEDIA arg0) {
                                        }

                                        @Override
                                        public void onStart(SHARE_MEDIA arg0) {
                                        }

                                    });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        this.facebookCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 判断Twitter是否授权
                    if (UMInfoAgent.isOauthed(mContext, SHARE_MEDIA.FACEBOOK)) {
                        facebookCb.setChecked(true);
                    } else {
                        // 设置按钮选中状态为false
                        facebookCb.setChecked(false);
                        try {
                            mController.doOauthVerify(mContext, SHARE_MEDIA.FACEBOOK,
                                    new UMAuthListener() {
                                        @Override
                                        public void onError(SocializeException e,
                                                SHARE_MEDIA platform) {
                                        }

                                        @Override
                                        public void onComplete(Bundle value,
                                                SHARE_MEDIA platform) {
                                            if (value != null
                                                    && !TextUtils.isEmpty(value
                                                            .getString("uid"))) {
                                                Toast.makeText(mContext, "授权成功.",
                                                        Toast.LENGTH_SHORT).show();
                                                facebookCb.setChecked(true);
                                            } else {
                                                Toast.makeText(mContext, "授权失败",
                                                        Toast.LENGTH_SHORT).show();
                                                facebookCb.setChecked(false);
                                            }
                                        }

                                        @Override
                                        public void onCancel(SHARE_MEDIA arg0) {
                                        }

                                        @Override
                                        public void onStart(SHARE_MEDIA arg0) {
                                        }

                                    });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        this.sinaCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 判断Twitter是否授权
                    if (UMInfoAgent.isOauthed(mContext, SHARE_MEDIA.SINA)) {
                        sinaCb.setChecked(true);
                    } else {
                        // 设置按钮选中状态为false
                        sinaCb.setChecked(false);
                        try {
                            mController.doOauthVerify(mContext, SHARE_MEDIA.SINA,
                                    new UMAuthListener() {
                                        @Override
                                        public void onError(SocializeException e,
                                                SHARE_MEDIA platform) {
                                        }

                                        @Override
                                        public void onComplete(Bundle value,
                                                SHARE_MEDIA platform) {
                                            if (value != null
                                                    && !TextUtils.isEmpty(value
                                                            .getString("uid"))) {
                                                Toast.makeText(mContext, "授权成功.",
                                                        Toast.LENGTH_SHORT).show();
                                                sinaCb.setChecked(true);
                                            } else {
                                                Toast.makeText(mContext, "授权失败",
                                                        Toast.LENGTH_SHORT).show();
                                                sinaCb.setChecked(false);
                                            }
                                        }

                                        @Override
                                        public void onCancel(SHARE_MEDIA arg0) {
                                        }

                                        @Override
                                        public void onStart(SHARE_MEDIA arg0) {
                                        }

                                    });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        this.qqCb.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 判断Twitter是否授权
                    if (UMInfoAgent.isOauthed(mContext, SHARE_MEDIA.TENCENT)) {
                        qqCb.setChecked(true);
                    } else {
                        // 设置按钮选中状态为false
                        qqCb.setChecked(false);
                        try {
                            mController.doOauthVerify(mContext, SHARE_MEDIA.TENCENT,
                                    new UMAuthListener() {
                                        @Override
                                        public void onError(SocializeException e,
                                                SHARE_MEDIA platform) {
                                        }

                                        @Override
                                        public void onComplete(Bundle value,
                                                SHARE_MEDIA platform) {
                                            if (value != null
                                                    && !TextUtils.isEmpty(value
                                                            .getString("uid"))) {
                                                Toast.makeText(mContext, "授权成功.",
                                                        Toast.LENGTH_SHORT).show();
                                                qqCb.setChecked(true);
                                            } else {
                                                Toast.makeText(mContext, "授权失败",
                                                        Toast.LENGTH_SHORT).show();
                                                qqCb.setChecked(false);
                                            }
                                        }

                                        @Override
                                        public void onCancel(SHARE_MEDIA arg0) {
                                        }

                                        @Override
                                        public void onStart(SHARE_MEDIA arg0) {
                                        }

                                    });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

    }

    /**
     * 获取传递的参数
     */
    private void getBundle() {
        Intent intent = getIntent();
        businessId = intent.getStringExtra("businessId");
        businessName = intent.getStringExtra("businessName");
        draftSignInfo = (SignEntity) intent.getSerializableExtra("signInfo");
    }

    /**
     * 获取传递的参数
     */
    private void setViews() {
        if (draftSignInfo != null) {
            businessId = draftSignInfo.getSellerId();
            businessName = draftSignInfo.getSellerName();
            String content = draftSignInfo.getSginNaiyo();
            if (!StringUtil.isNullOrEmpty(content)) {
                signContentEt.setText(content);
            }
            Float totalStar = draftSignInfo.getSellerStar();
            if (totalStar != null) {
                signStarRb.setRating(totalStar);
            }

        }
    }

    /**
     * 验证数据
     */
    private boolean verifyData() {
        if (StringUtil.isNullOrEmpty(signContent)) {
            showLongToast(this, "请输入签到内容！", true);
            return false;
        }
        if (signStar == 0) {
            showLongToast(this, "请选择评价分数！", true);
            return false;
        }

        return true;
    }

    /**
     * 获取上传图片数据
     */
    private void requestAddSignData() {
        if (StringUtil.isNullOrEmpty(businessId)) {
            return;
        }
        if (commonUserInfo == null) {
            return;
        }
        AsyncLoadData ald = new AsyncLoadData(this, "提交中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> addSignParamMap = new HashMap<String, Object>();
                        addSignParamMap.put("sellerId", businessId);
                        addSignParamMap.put("sellerStar", signStar);
                        if (!StringUtil.isNullOrEmpty(fileBase64)) {
                            addSignParamMap.put("sginImg", fileBase64);
                        }
                        addSignParamMap.put("sginNaiyo", signContent);
                        addSignParamMap.put("userId",
                                commonUserInfo.getUserId());
                        // addReviewParamMap.put("language", "1");

                        // 发送请求
                        byte[] commentItemList = HttpUtil.requestByPost(
                                AddSignedActivity.this, Constants.ADD_SIGN_API,
                                addSignParamMap);
                        if (commentItemList != null) {

                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        showShortToast(AddSignedActivity.this, "温馨提示：签到成功！");
                        finish();
                    }

                });
        ald.execute(0);

    }

    private void doShare() {
        List<SHARE_MEDIA> share = new ArrayList<SHARE_MEDIA>();
        if (twitterCb.isChecked()) {
            share.add(SHARE_MEDIA.TWITTER);
        }
        if (facebookCb.isChecked()) {
            share.add(SHARE_MEDIA.FACEBOOK);
        }

        if (sinaCb.isChecked()) {
            share.add(SHARE_MEDIA.SINA);
        }

        if (qqCb.isChecked()) {
            share.add(SHARE_MEDIA.TENCENT);
        }
        SHARE_MEDIA[] shareArr = new SHARE_MEDIA[4];
        shareArr = share.toArray(shareArr);
        // 设置分享内容
        mController.setShareContent(signContent);
        mController.postShareMulti(mContext, new MulStatusListener() {
            @Override
            public void onStart() {
                // Toast.makeText(mContext, "开始分享.", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(MultiStatus snsSt, int st,
                    SocializeEntity entity) {
                // Toast.makeText(mContext, snsSt.toString(), Toast.LENGTH_LONG)
                // .show();
            }
        }, shareArr);

    }

    /**
     * 初始化参数
     */
    private void initQQ() {
        oAuth = new OAuthV2(ShareConfig.QQ_Redirect_Uri);
        oAuth.setClientId(ShareConfig.QQ_App_Key);
        oAuth.setClientSecret(ShareConfig.QQ_App_Seret);

        // 关闭OAuthV2Client中的默认开启的QHttpClient。
        OAuthV2Client.getQHttpClient().shutdownConnection();
    }

    /**
     * 分享至Sina
     */
    private void shareToSina() {
        AsyncLoadData ald = new AsyncLoadData(this, new AsyncAction() {

            @Override
            public void doLoad() throws Exception {
                String filePath = BitmapUtil.saveMyBitmap(headBitmap,
                        String.valueOf(System.currentTimeMillis()));
                ShareAction.shareWithImgToQQ(AddSignedActivity.this,
                        signContent, filePath);
            }

            @Override
            public void loadEnd() throws Exception {
            }

        });
        ald.execute(0);
    }

    /**
     * 分享至QQ
     */
    private void shareToQQ() {
        AsyncLoadData ald = new AsyncLoadData(this, new AsyncAction() {

            @Override
            public void doLoad() throws Exception {
                String filePath = BitmapUtil.saveMyBitmap(headBitmap,
                        String.valueOf(System.currentTimeMillis()));
                ShareAction.shareWithImgToQQ(AddSignedActivity.this,
                        signContent, filePath);
            }

            @Override
            public void loadEnd() throws Exception {
            }

        });
        ald.execute(0);
    }

    public static final int PHOTOHRAPH = 1;// 拍照
    public static final int PHOTOZOOM = 2; // 缩放
    public static final int PHOTORESOULT = 3;// 结果

    public static final String IMAGE_UNSPECIFIED = "image/*";

    private byte[] mContent;

    private void showImageMenuDialog() {
        final String[] arrayFruit = new String[] {
                "相机拍摄", "手机相册"
        };

        final Dialog alertDialog = new AlertDialog.Builder(
                AddSignedActivity.this).setTitle("图片来源")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setItems(arrayFruit, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // switch (which) {
                        // case 0:
                        // Intent cameraI = new Intent(
                        // MediaStore.ACTION_IMAGE_CAPTURE);
                        // cameraI.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                        // .fromFile(new File(Environment
                        // .getExternalStorageDirectory(),
                        // "temp.jpg")));
                        // startActivityForResult(cameraI, PHOTOHRAPH);
                        // break;
                        // case 1:
                        // Intent pictureI = new Intent(Intent.ACTION_PICK,
                        // null);
                        // pictureI.setDataAndType(
                        // MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        // IMAGE_UNSPECIFIED);
                        // startActivityForResult(pictureI, PHOTOZOOM);
                        // break;
                        //
                        // default:
                        // break;
                        // }
                        if (which == 0) {
                            Intent getImageByCamera = new Intent(
                                    MediaStore.ACTION_IMAGE_CAPTURE);
                            startActivityForResult(getImageByCamera, PHOTOHRAPH);
                        } else {
                            Intent getImage = new Intent(
                                    Intent.ACTION_GET_CONTENT, null);
                            getImage.addCategory(Intent.CATEGORY_OPENABLE);
                            getImage.setType(IMAGE_UNSPECIFIED);
                            startActivityForResult(getImage, 0);
                        }
                    }
                }).create();
        alertDialog.show();
    }

    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        // if (requestCode == PHOTOHRAPH) {
        // // 设置文件保存路径这里放在跟目录下
        // File picture = new File(Environment.getExternalStorageDirectory()
        // + "/temp.jpg");
        // startPhotoZoom(Uri.fromFile(picture));
        // }
        // if (intent == null) {
        // return;
        // }
        // // 相册
        // // 读取相册缩放图片
        // if (requestCode == PHOTOZOOM) {
        // startPhotoZoom(intent.getData());
        // }
        //
        // // 处理结果
        // if (requestCode == PHOTORESOULT) {
        // Bundle extras = intent.getExtras();
        // if (extras != null) {
        // headBitmap = extras.getParcelable("data");
        // this.ideaImageIv.setImageBitmap(headBitmap);
        // ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        // headBitmap.compress(CompressFormat.JPEG, 100, bStream);
        //
        // byte[] bytes = bStream.toByteArray();
        // fileBase64 = Base64.encodeToString(bytes, Base64.DEFAULT);
        // // 设置创意类型
        // ideaType = TYPE_IMAGE;
        // // uploadFile();
        // }
        // }
        switch (requestCode) {
            case 0:
                try {
                    ContentResolver resolver = getContentResolver();
                    // 获得图片的uri
                    Uri originalUri = intent.getData();
                    // 将图片内容解析成字节数组
                    mContent = readStream(resolver.openInputStream(Uri
                            .parse(originalUri.toString())));
                    if (mContent == null) {
                        return;
                    }
                    // 将字节数组转换为ImageView可调用的Bitmap对象
                    headBitmap = getPicFromBytes(mContent, null);
                    // //把得到的图片绑定在控件上显示
                    // this.ideaImageIv.setImageBitmap(headBitmap);
                    // BitmapDrawable bd = new BitmapDrawable(getResources(),
                    // headBitmap);
                    uploadImageIv.setImageBitmap(headBitmap);
                    // imgDeleteIv.setVisibility(0);
                    fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
                } catch (Exception e) {
                    // System.out.println(e.getMessage());
                }
                break;
            case 1:
                try {
                    super.onActivityResult(requestCode, resultCode, intent);
                    if (intent == null) {
                        return;
                    }
                    Bundle extras = intent.getExtras();
                    headBitmap = (Bitmap) extras.get("data");
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    headBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    mContent = baos.toByteArray();
                    fileBase64 = Base64.encodeToString(mContent, Base64.DEFAULT);
                    // 设置创意类型
                    // 把得到的图片绑定在控件上显示
                    // this.ideaImageIv.setImageBitmap(headBitmap);
                    // BitmapDrawable bd = new BitmapDrawable(getResources(),
                    // headBitmap);
                    // ideaImageIv.setBackgroundDrawable(bd);
                    uploadImageIv.setImageBitmap(headBitmap);
                    // imgDeleteIv.setVisibility(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;

            default:
                break;
        }
    }

    public static Bitmap getPicFromBytes(byte[] bytes,
            BitmapFactory.Options opts) {
        if (bytes != null)
            if (opts != null)
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
                        opts);
            else
                return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        return null;
    }

    public static byte[] readStream(InputStream inStream) throws Exception {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        byte[] data = outStream.toByteArray();
        outStream.close();
        inStream.close();
        return data;

    }
}
